package com.koron.ticket.work.logicticket.hightask;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.koron.bean.base.Response;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.bean.workflow.RedirectQuery;
import com.koron.bean.workflow.WorkflowController;
import com.koron.common.core.business.print.ReportTask;
import com.koron.common.core.business.workflow.bean.po.SysWorkflow;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.ticket.utils.PrintUtils;
import com.koron.ticket.work.common.bean.FifteenTables;
import com.koron.ticket.work.enums.PrintTemplate;
import com.koron.ticket.work.logicticket.hightask.bean.HighTaskDto;
import com.koron.ticket.work.logicticket.hightask.bean.YcHightaskTicketPrint;
import com.koron.ticket.work.workPermit.bean.WorkPermit;
import com.koron.ticket.work.workend.bean.WorkEnd;
import com.koron.ticket.work.workflow.bean.WorkFlow;
import com.koron.ticket.work.workflow.mapper.WorkFlowMapper;
import com.koron.ticket.work.workticket.mapper.WorkTicketMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("work/hightask")
@Api(tags = "两票管理-工作票-高处作业票")
public class HighTaskController implements WorkflowController {

    private String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }

    private EamUser getCurrUser() {
        return ThreadLocalContext.get();
    }

    @Autowired
    private HighTaskService hightaskservice;


    /**
     * 填写阶段，保存功能
     * 1. 保存当前的数据（新增/更新）
     *
     * @param dto
     * @return Response对象
     * @version 1.0
     * @see Response
     * @see FifteenTables
     */
    @PostMapping("writeSave")
    @ApiOperation("填写-保存")
    public Response writeSave(@RequestBody HighTaskDto dto) {
        return ADOConnection.runTask(getCurrDs(), hightaskservice, "writeSave", Response.class, dto);
    }

    /**
     * 打印预览功能：
     * 1. 所有状态的打印预览都是这个接口
     * 2. 接口返回的是一个url，用于拉起打印控件的打印预览
     * 3. 需要先安装打印控件，并确保控件正常运行
     *
     * @param id
     * @return Response对象
     * @version 1.0
     * @see Response
     */
    @GetMapping("printById")
    @ApiOperation("打印预览")
    public Response print(@RequestParam("id") String id) {
        List<YcHightaskTicketPrint> printList = ADOConnection.runTask(getCurrDs(), hightaskservice, "getPrintData", ArrayList.class, id);
        String printTemplateId = PrintUtils.getDefaultPrintTemplateId(PrintTemplate.HighTaskTicket.getType());
        String url = ReportTask.printData(getCurrUser(), printTemplateId, printList);//存储打印数据，以及返回打印地址
        return Response.success("获取成功，拿返回地址回调打印", url);
    }

//    /**
//     * 填写阶段，提交功能
//     * 1. 保存当前的数据（新增/更新）
//     * 2. 初始化工作流
//     * 3. 记录操作人
//     *
//     * @param fifteenTables
//     * @return Response对象
//     * @version 1.0
//     * @see Response
//     * @see FifteenTables
//     */
//    @PostMapping("writeSubmit")
//    @ApiOperation("填写-提交")
//    public Response writeSubmit(@RequestBody FifteenTables fifteenTables) {
//        return ADOConnection.runTask(getCurrDs(), electricalFirstService, "writeSubmit", Response.class, fifteenTables);
//    }

    @PostMapping("signSave")
    @ApiOperation("待签发-保存")
    public Response signSave(@RequestBody WorkFlow workFlow) {
        return ADOConnection.runTask(getCurrDs(), hightaskservice, "signSave", Response.class, workFlow);
    }

    @PostMapping("acceptSave")
    @ApiOperation("待接收-保存")
    public Response acceptSave(@RequestBody WorkFlow workFlow) {
        return ADOConnection.runTask(getCurrDs(), hightaskservice, "acceptSave", Response.class, workFlow);
    }

    @PostMapping("permitSave")
    @ApiOperation("待许可-保存")
    public Response permitSave(@RequestBody WorkPermit workPermit) {
        return ADOConnection.runTask(getCurrDs(), hightaskservice, "permitSave", Response.class, workPermit);
    }

    /**
     * 工作票待终结阶段，保存功能
     * 1. 保存工作票待终结阶段的数据（新增/更新）
     * 2. 保存签名的数据（新增/更新）
     *
     * @param workEnd
     * @return Response对象
     * @version 1.0
     * @see Response
     * @see WorkEnd
     */
    @PostMapping("ticketEndSave")
    @ApiOperation("工作票待终结-保存")
    public Response ticketEndSave(@RequestBody WorkEnd workEnd) {
        return ADOConnection.runTask(getCurrDs(), hightaskservice, "ticketEndSave", Response.class, workEnd);
    }

    /**
     * 工作流回调接口
     * 1. 除了填写阶段，和已归档前一个阶段（不同的票不一样）都要走这个接口
     * 2. 处理驳回和通过的情况
     *
     * @param redirectQuery
     * @return Response对象
     * @version 1.0
     * @see Response
     */
//    @PostMapping("/workflowUpdate")
//    @ApiOperation(value = "工作流回调接口",hidden = true)
    @Override
    public Response updateState(@RequestBody RedirectQuery redirectQuery) {
        return ADOConnection.runTask(getCurrDs(), hightaskservice, "workflowUpdate", Response.class, redirectQuery);
    }

    /**
     * 工作流结束接口：
     * 1. 已归档签一个阶段的提交，会走这个接口处理
     *
     * @param redirectQuery
     * @return Response对象
     * @version 1.0
     * @see Response
     */
//    @PostMapping("/workflowUpdateEnd")
//    @ApiOperation(value = "结束时的修改方法, 非前端接口",hidden = true)
    @Override
    public Response updateEnd(@RequestBody RedirectQuery redirectQuery) {
        return ADOConnection.runTask(getCurrDs(), hightaskservice, "workflowUpdateEnd", Response.class, redirectQuery);
    }

    /**
     * 工作流作废：
     * 1. 工作流作废时的接口
     * 2. 作废仅变更工作票的状态；其他数据保留
     *
     * @param redirectQuery
     * @return Response对象
     * @version 1.0
     * @see Response
     */
//    @PostMapping("/workflowUpdateCancel")
//    @ApiOperation(value = "作废时的修改方法, 非前端接口",hidden = true)
    @Override
    public Response updateCancel(@RequestBody RedirectQuery redirectQuery) {
        return ADOConnection.runTask(getCurrDs(), hightaskservice, "workflowUpdateCancel", Response.class, redirectQuery);
    }


    @PostMapping("/ishide")
    @ApiOperation("是否展示许可2")
    public Response ishide(@RequestParam("id") String id) {
        Boolean flag = ADOConnection.runTask(getCurrDs(), sessionFactory -> {
            SysWorkflow sysworkflow = sessionFactory.getMapper(WorkTicketMapper.class).querypermit(id);
            WorkFlowMapper workflowmapper = sessionFactory.getMapper(WorkFlowMapper.class);

            if (StrUtil.isBlank(sysworkflow.getCurNodeCode())) {
                return true;
            }
            List<WorkFlow> workFlows = workflowmapper.queryByWorkTicketIdIn(CollUtil.newArrayList(id));
            boolean nodeflag = workFlows.stream().anyMatch(w -> StrUtil.isNotBlank(w.getType()) && w.getStatus() == 5 && w.getType().equals("name1"));
            if (StrUtil.equals(sysworkflow.getCurNodeCode(), "call-PERMIT2") || nodeflag) {
                return false;
            }
            return true;
        }, Boolean.class);

        return Response.ok(flag);
    }
}
